package com.kstech.exccheck.domain.check;

import android.util.Log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.kstech.exccheck.communication.CommandResp;
import com.kstech.exccheck.communication.CommandSender;
import com.kstech.exccheck.config.vo.CheckItemVO;
import com.kstech.exccheck.db.CheckItemDao;
import com.kstech.exccheck.db.CheckItemDetailDao;
import com.kstech.exccheck.receiver.ReceivedDataKey;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.DateUtil;
import com.kstech.exccheck.view.check.SingleCheckActivity;
import com.kstech.exccheck.view.upload.Globals;

import J1939.J1939_DataVar_ts;


/**
 * 
 * @author wanghaibin
 * @created 2016-10-23 ����2:50:24
 * @since v1.0
 */
public class SingleCheckTask  implements ReceivedDataKey {

//	private static ExecutorService executorService = Executors
//			.newSingleThreadExecutor();

	private static SingleCheckActivity singleCheckActivity;

	private CheckWorker worker;

	public SingleCheckTask(SingleCheckActivity singleCheckActivity) {
		this.singleCheckActivity = singleCheckActivity;
	}

	public void start(CheckItemEntity checkItemEntity) {

		Globals.WIFINotify = true;
//		worker = new CheckWorker(checkItemEntity);
//		executorService.execute(worker);
		// 使用线程池，第二次run方法不执行
		worker = new CheckWorker(checkItemEntity);
		new Thread(worker).start();
	}

	/**
	 * 点击停止检测按钮
	 */
	public void stop() {
		worker.setStop(true);
	}

	private static class CheckWorker implements Runnable {
		private boolean stop = false;
		private CheckItemEntity checkItemEntity;
		// 获取检查项参数头
		private List<CheckItemParamValueVO> headers;
		// item 配置
		CheckItemVO checkItemVO;

		public CheckWorker(CheckItemEntity checkItemEntity){
			this.checkItemEntity = checkItemEntity;
			headers = AppContext.getModelFile()
					.getCheckItemVO(checkItemEntity.getItemId())
					.getParamNameList();
			// 通过 checkItemEntity 实体对象，找到配置文件中的对应VO
			checkItemVO = AppContext.getModelFile().getCheckItemVO(
					checkItemEntity.getItemId());
		}
		@Override
		public void run() {
//			Globals.list32.clear();
//			Globals.list33.clear();
			/*<!-- 检测项目使用的提示信息
            ReadyMsg    - 检测准备就绪提示,在发出“准备检测”命令并收到“准备就绪”应答后显示
            NotReadyMsg - 检测准备未就绪（未达检测条件）提示，在发出“准备检测”命令并收到“传感器故障”应答时显示
            AbortMsg    - 检测中止提示，在检测过程中选择“中止检测”发出中止命令且收到“本次测量中止”时显示
            OkMsg       - 检测完成提示，在收到“检测完成”应答时显示
         	-->*/
			// 判断是否人工终止，进行处理
			if (isStop()){return;}
			// 发送开始检测命令
			CommandSender.sendStartCheckCommand(checkItemEntity.getItemId(),
					checkItemEntity.getSumTimes() + 1);
			// 启动计时器，通知UI开始检测
			singleCheckActivity.checkUINotice("发送开始检测命令",CheckTimer.START);

			Globals.isSingleChecking = true;
			// 开始检测命令响应轮循
			while (true) {
				// 判断是否人工终止，进行处理
				if (isStop()){
					Globals.isSingleChecking = false;
					return;
				}

				int totalSec = singleCheckActivity.getCheckTimer()
						.getTotalSec();
				Log.e("startCheckCommandResp",totalSec+"--------------------");
				if (totalSec >= checkItemVO.getQcTimeout()) {
					Globals.isSingleChecking = false;
					// 判断是否人工终止，进行处理
					if (isStop()){return;}
					// 保存记录，结论，通讯超时
					CheckItemDetailDao.insertDetailAndUpdateItem(CheckItemDetailStatusEnum.CONNECT_TIMEOUT.getCode(),checkItemEntity,headers,checkItemVO);
					// 发送开始检测命令后，没有对应的应答，已经超时，通知UI线程，程序终止
					singleCheckActivity.checkUINotice("开始检测命令响应超时，请确认检线连接是否正常",CheckTimer.STOP);
					return;
				} else {
					String startCheckCommandResp = CommandResp
							.getStartCheckCommandResp(
									checkItemEntity.getItemId(),
									checkItemEntity.getSumTimes() + 1);
					Log.e("startCheckCommandResp",startCheckCommandResp+"---------------");
					if ("".equals(startCheckCommandResp)) {
						// 还没有响应，继续轮循
					} else if ("正在检测".equals(startCheckCommandResp)) {
						// 检测指示码
						J1939_DataVar_ts checkCodeDSItemResp = AppContext.getModelFile()
								.getDataSetVO().getCheckCodeDSItemResp();
						String progressMsg = "";
						if(checkCodeDSItemResp.isFloatType()) {
							progressMsg = checkItemVO.getProgressMsg(String.valueOf(checkCodeDSItemResp.getFloatValue()));
						} else {
							progressMsg = checkItemVO.getProgressMsg(String.valueOf(checkCodeDSItemResp.getValue()));
						}
						String content = "正在检测 - - - ";
						if (progressMsg != null && !progressMsg.equals("")) {
							content = AppContext.getResConfig().getResourceVO().getMsg(progressMsg).getContent();
						}
						// 通知UI线程检测进度，继续循环判断状态，至检测完成
						singleCheckActivity.checkUINotice(content, "");

					} else if ("检测完成".equals(startCheckCommandResp)) {
						Globals.isSingleChecking = false;
						String detailStatus = CheckItemDetailStatusEnum.PASS.getCode();
						for (CheckItemParamValueVO h : headers) {
							// 从数据区中获取 检查参数对应的数据区
							J1939_DataVar_ts dsItem = AppContext.getModelFile()
									.getDataSetVO().getDSItem(h.getParam());
							//数值转换
							byte bDataDec = dsItem.bDataDec;
							StringBuffer sb = new StringBuffer();
							if (bDataDec!=0) {
								sb.append(".");
								for (int i=0;i < bDataDec;i++) {
									sb.append("0");
								}
							}
							DecimalFormat decimalFormat=new DecimalFormat(sb.toString());
							if (dsItem.isFloatType()) {
								Float value = dsItem.getFloatValue();
								Log.e("MIAO","收到得知values"+value);
								String formatValue = decimalFormat.format(value);
								if(".".equals(formatValue.substring(0,1))) {
									formatValue = "0" + formatValue;
								}
								if("0".equals(formatValue)){
									formatValue = "0";
								}
								Float checkvalue = Float.parseFloat(formatValue);
								h.setValue(formatValue);
								Log.e("MIAO","收到得知"+formatValue);
								// 有一个参数不合格，那么当次检测不合格
								if (Float.valueOf(h.getValidMin()) > checkvalue
										|| checkvalue > Float.valueOf(h
										.getValidMax())) {
									detailStatus = CheckItemDetailStatusEnum.UN_PASS.getCode();
								}
							} else {
								h.setValue(dsItem.getValue() + "");
								// 有一个参数不合格，那么当次检测不合格
								if (Long.valueOf(h.getValidMin()) > dsItem.getValue()
										|| dsItem.getValue() > Long
										.valueOf(h.getValidMax())) {
									detailStatus = CheckItemDetailStatusEnum.UN_PASS.getCode();
								}
							}
						}
						// 插入详情记录，更新项目记录
						CheckItemDetailDao.insertDetailAndUpdateItem(detailStatus,checkItemEntity,headers,checkItemVO);
						String okMsg = checkItemVO.getOkMsg();
						String content = "";
						if (okMsg != null && !okMsg.equals("")) {
							content = AppContext.getResConfig().getResourceVO().getMsg(okMsg).getContent();
						}
						// 通知UI线程检测完成，程序终止
						singleCheckActivity.checkUINotice(content, CheckTimer.STOP);
						for (CheckItemParamValueVO h : headers) {
							// 从数据区中获取 检查参数对应的数据区
							J1939_DataVar_ts dsItem = AppContext.getModelFile()
									.getDataSetVO().getDSItem(h.getParam());
							//数值转换
							byte bDataDec = dsItem.bDataDec;
							StringBuffer sb = new StringBuffer();
							if (bDataDec!=0) {
								sb.append(".");
								for (int i=0;i < bDataDec;i++) {
									sb.append("0");
								}
							}
							DecimalFormat decimalFormat=new DecimalFormat(sb.toString());
							if (dsItem.isFloatType()) {
								Float value = 0f;
								String formatValue = decimalFormat.format(value);
								if(".".equals(formatValue.substring(0,1))) {
									formatValue = "0" + formatValue;
								}
								if("0".equals(formatValue)){
									formatValue = "0";
								}
								h.setValue(formatValue);
							}
						}

						return;
					} else if ("传感器故障".equals(startCheckCommandResp)||"检测失败".equals(startCheckCommandResp)) {
						for (CheckItemParamValueVO h : headers) {
							// 从数据区中获取 检查参数对应的数据区
							J1939_DataVar_ts dsItem = AppContext.getModelFile()
									.getDataSetVO().getDSItem(h.getParam());
							//数值转换
							byte bDataDec = dsItem.bDataDec;
							StringBuffer sb = new StringBuffer();
							if (bDataDec!=0) {
								sb.append(".");
								for (int i=0;i < bDataDec;i++) {
									sb.append("0");
								}
							}
							DecimalFormat decimalFormat=new DecimalFormat(sb.toString());
							if (dsItem.isFloatType()) {
								Float value = 0f;
								String formatValue = decimalFormat.format(value);
								if(".".equals(formatValue.substring(0,1))) {
									formatValue = "0" + formatValue;
								}
								if("0".equals(formatValue)){
									formatValue = "0";
								}
								h.setValue(formatValue);
							}
						}
						// 检测指示码
						J1939_DataVar_ts checkCodeDSItemResp = AppContext.getModelFile()
								.getDataSetVO().getCheckCodeDSItemResp();
						String errorMsg = "";
						if(checkCodeDSItemResp.isFloatType()) {
							errorMsg = checkItemVO.getErrorMsg(String.valueOf(checkCodeDSItemResp.getFloatValue()));
						} else {
							errorMsg = checkItemVO.getErrorMsg(String.valueOf(checkCodeDSItemResp.getValue()));
						}
						String content = "";
						if (errorMsg != null && !errorMsg.equals("")) {
							content = AppContext.getResConfig().getResourceVO().getMsg(errorMsg).getContent();
						}

						// 判断是否人工终止，进行处理
						if (isStop()){return;}

						// 保存记录，结论，传感器故障
						CheckItemDetailDao.insertDetailAndUpdateItem(CheckItemDetailStatusEnum.OTHER.getCode(),checkItemEntity,headers,checkItemVO);

						// 传感器故障,则通知UI。程序终止
						singleCheckActivity.checkUINotice(content, CheckTimer.STOP);
						Globals.isSingleChecking = false;
						return;
					}
				}
				// 间隔100ms，遍历应答区域，是否已经有响应，获取数据后，不将数据应答区置空。与老吴商量
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		public void setStop(boolean stop) {
			this.stop = stop;
		}

		public boolean isStop() {
			if (stop) {

				for (CheckItemParamValueVO h : headers) {
					// 从数据区中获取 检查参数对应的数据区
					J1939_DataVar_ts dsItem = AppContext.getModelFile()
							.getDataSetVO().getDSItem(h.getParam());
					//数值转换
					byte bDataDec = dsItem.bDataDec;
					StringBuffer sb = new StringBuffer();
					if (bDataDec!=0) {
						sb.append(".");
						for (int i=0;i < bDataDec;i++) {
							sb.append("0");
						}
					}
					DecimalFormat decimalFormat=new DecimalFormat(sb.toString());
					if (dsItem.isFloatType()) {
						Float value = 0f;
						String formatValue = decimalFormat.format(value);
						if(".".equals(formatValue.substring(0,1))) {
							formatValue = "0" + formatValue;
						}
						if("0".equals(formatValue)){
							formatValue = "0";
						}
						h.setValue(formatValue);
					}
				}

				// 发送终止检测命令
				CommandSender.sendStopCheckCommand(checkItemEntity.getItemId(),
						checkItemEntity.getSumTimes() + 1);
				// 保存记录，结论，人工终止
				CheckItemDetailDao.insertDetailAndUpdateItem(CheckItemDetailStatusEnum.MANUAL_END.getCode()
						,checkItemEntity,headers,checkItemVO);

				// 通知UI页面，人工终止信息
				singleCheckActivity.checkUINotice("人工终止检测",CheckTimer.STOP);
			}
			return stop;
		}
	}
//
//	private static void catchData() {
//		FileOutputStream fileOutputStream = null;
//		try {
//            fileOutputStream = new FileOutputStream("/storage/sdcard1/data_yougang.txt", true);
//            PrintStream printStream = new PrintStream(fileOutputStream);
//            printStream.println("0xff2f---------------------------------------------");
//			for (String s:Globals.list2F) {
//				printStream.println(s);
//			}
//			printStream.println("0xff30---------------------------------------------");
//			for (String s:Globals.list30) {
//				printStream.println(s);
//			}
//			printStream.println("0xff31--------------------------------------------");
//			for (String s:Globals.list31) {
//				printStream.println(s);
//			}
//			printStream.println("0xff32---------------------------------------------");
//			for (String s:Globals.list32) {
//				printStream.println(s);
//			}
//			printStream.println("0xff33---------------------------------------------");
//			for (String s:Globals.list33) {
//				printStream.println(s);
//			}
//			printStream.flush();
//            printStream.close();
//            fileOutputStream.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//	}


}
